package cn.chinaflame.pagodas.service;

import cn.chinaflame.pagodas.Result.Result;
import cn.chinaflame.pagodas.constant.Sysconst;
import cn.chinaflame.pagodas.utils.DateTimes;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import cn.chinaflame.pagodas.entity.PaBadLights;
import cn.chinaflame.pagodas.entity.PaEmailLog;
import cn.chinaflame.pagodas.utils.DateTimes;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import cn.chinaflame.pagodas.utils.email.Email;
import cn.chinaflame.pagodas.utils.email.EmailService;
import cn.chinaflame.pagodas.utils.excel.DownloadExcelUtil;
import cn.chinaflame.pagodas.vo.LightVO;

import static cn.chinaflame.pagodas.constant.Sysconst.AREAS;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;

import javax.servlet.http.HttpServletRequest;
import  javax.servlet.http.HttpServletResponse;
/**
 * 定时任务service
 *
 * @author created by boming
 * @date 2018年5月7日 下午3:32:11
 */
@Component
public class QuartzService {

    public final static long ONE_Minute = 60 * 1000;
    private static final Logger log = LoggerFactory.getLogger(QuartzService.class);
    public static long TranTimeoutMinute = -15;
    public static long PayTimeoutMinute = -30;
    public static long orderInterval = 16; //订单定时任务间隔时长，单位分钟
    public static long productPointInterval = 0; //供灯位置定时任务间隔时长，单位半分钟
    public static long orderCount = 0;
    public static long productPointCount = 0;
    public static long productPointTimeoutCount = 0;
    public static int i;
    @Autowired
    private PaProductPointService paProductPointService;
    @Autowired
    private PaOrderService paOrderService;
    @Autowired
    private PaBadLightsService paBadLightsService;
	@Autowired
    private Email email;
	
    @Autowired
    private EmailService emailService;
    
//    @Value("${mail.attachPath}")
//    private String mailattachPath;
//    
//    @Value("${mail.attachPathCentOs}")
//    private String mailattachPathCentOs;
    
    /**
     * 定时任务每分钟清一次
     */
//	@Scheduled(fixedRate = ONE_Minute)
    public void fixedRateJob() {
        i = i + 1;
        System.err.println("进入定时任务" + i + "分钟" + "定时任务已执行第" + i + "次");
        try {
            paProductPointService.clearLight();
        } catch (Exception e) {
            Result.create("ERROR", "定时任务清灯接口" + e.getMessage());
        }

    }

    /**
     * 订单状态定时任务
     * 处理未支付订单
     */
//    @Scheduled(fixedRate = 15000 * 60) 展示注解
    public void orderPayStatusUpdate() {
		log.info("订单状态定时任务start{}");
        //交易方式：CHARGE-充值；CASHOUT-提现；PAY-消费；REFUND-退款；
        //支付状态：0-待支付；1-支付中（等待回调）；2-支付成功；3-支付失败；4-交易超时；5-支付超时（长时间没收到回调通知）
        orderCount = 0;
        String nowDateTime = DateTimes.nowDateTime();
        //当前时间减去15分钟
        String transTimeout = DateTimes.addMinuteToStringDate(DateTimes.TIMESTAMP_PATTERN4, nowDateTime, TranTimeoutMinute);
        //当前时间减去30分钟
        String payTimeout = DateTimes.addMinuteToStringDate(DateTimes.TIMESTAMP_PATTERN4, nowDateTime, PayTimeoutMinute);
        paOrderService.orderPayStatusUpdate(transTimeout, payTimeout);
    }

    /**
     * 点灯/熄灯操作定时任务，暂时改成50000，原本为500
     */
    //@Scheduled(fixedRate = 5000000)
    public void productPointStatusUpdate() {
        while (productPointCount < productPointInterval) {
            productPointCount++;
        }
        productPointCount = 0;
        paProductPointService.productPointStatusUpdate();
    }

    //在零点零一分执行熄灯任务
    @Scheduled(cron = "0 01 0 * * ?")
    public void dinShiXiDeng() {
        paProductPointService.dinshiXidengApi();
    }
    /**
     * 订单超时灯状态修改及
     */
//    @Scheduled(fixedRate = 500)       展示注解
    public void productPointStatusUpdateForTimeout() {
        while (productPointTimeoutCount < productPointInterval) {
        	productPointTimeoutCount++;
        }
        productPointTimeoutCount = 0;
        paProductPointService.productPointStatusUpdateForTimeout();
    }
    
    
    /**
     * 定时寻灯接口
     * @return
     */
    public int[] scheduledLightSearch(String lightnos) {
    	log.info("QuartzService:scheduledLightSearch:lightnos={}",lightnos);
    	List<LightVO> lights =paProductPointService.lightCheck(lightnos);
    	int[] result = paBadLightsService.batchAddBadLight(lights);
    	log.info("QuartzService:scheduledLightSearch:result={}",result);
    	return result;
    }
    /**
     * 定时寻灯接口
     * @return
     */
    public List<Integer> scheduledLightSearch1(String areano) {
    	log.info("QuartzService:scheduledLightSearch1:areano={}",areano);
    	List<String> lights = paProductPointService.getLightsByArea(areano);
    	String lightnos =  String.join(",",lights);
    	List<LightVO> lightvos = paProductPointService.lightCheck(lightnos);
    	List<Integer> result = Lists.newArrayList();
    	for(LightVO vo:lightvos) {
    		if(vo.getResult() == 0) {
    			int n = paBadLightsService.addBadLight(vo);
    			result.add(n);
    		}
    	}
    	log.info("QuartzService:scheduledLightSearch1:result={}",result);
    	return result;
    }
    /**
     * 定时寻灯接口
     * @return
     */
    @Scheduled(cron="${lightcheck.scheduled}")
    public void scheduledLightSearch2() {
    	log.info("######scheduledLightSearch2 invoked:AREAS={}",JSONArray.toJSONString(AREAS));
    	if(AREAS != null && AREAS.size() > 0) {
    		for(String areano:AREAS) {
		    	log.info("areano={}",areano);
		    	List<String> lights = paProductPointService.getLightsByArea(areano);
		    	String lightnos =  String.join(",",lights);
		    	List<LightVO> lightvos = paProductPointService.lightCheck(lightnos);
		    	List<Integer> result = Lists.newArrayList();
		    	for(LightVO vo:lightvos) {
		    		if(vo.getResult() == 0) {
		    			int n = paBadLightsService.addBadLight(vo);
		    			result.add(n);
		    		}
		    	}
		    	log.info("QuartzService:scheduledLightSearch2:result={}",result);
    		}
    	}
    }
    
    /**
     * 
     * @param request
     * @param response
     */
//    @Scheduled(cron="${mail.scheduled}")
//    public void schedeledMail() {
//    	String yesterday = DateTimes.getYesterday();
//    	log.info("######scheduledLightSearch2 invoked:yesterday={}",yesterday);
//    	List<PaBadLights> list = paBadLightsService.findByCreatetime(yesterday);
//    	if(list != null && list.size() > 0) {
//		    	String sheetName =  yesterday+"异常灯号";
//		    	String fname =  sheetName+".xlsx";
//		    	String fpath = mailattachPath;
//		//			DownloadExcelUtil excel = new DownloadExcelUtil (response,fileName,sheetName);
//				DownloadExcelUtil.createExcel(Sysconst.BADLIGHTSTITLES,sheetName,fpath,fname,list) ;
//				email.setFileAffix(new String[] {fpath+fname});
//				try {
//					email.setBody(StringUtils.isNotBlank(email.getBody())?new String(email.getBody().getBytes("ISO-8859-1"),"UTF-8"):"");
//					email.setFrom(StringUtils.isNotBlank(email.getFrom())?new String(email.getFrom().getBytes("ISO-8859-1"),"UTF-8"):"");
//					email.setSendTo(StringUtils.isNotBlank(email.getSendTo())?new String(email.getSendTo().getBytes("ISO-8859-1"),"UTF-8"):"");
//					email.setCopyTo(StringUtils.isNotBlank(email.getCopyTo())?new String(email.getCopyTo().getBytes("ISO-8859-1"),"UTF-8"):"");
//					email.setAttachPath(StringUtils.isNotBlank(email.getAttachPath())?new String(email.getAttachPath().getBytes("ISO-8859-1"),"UTF-8"):"");
//					email.setSendErr(StringUtils.isNotBlank(email.getSendErr())?new String(email.getSendErr().getBytes("ISO-8859-1"),"UTF-8"):"");
//					email.setSendSucc(StringUtils.isNotBlank(email.getSendSucc())?new String(email.getSendSucc().getBytes("ISO-8859-1"),"UTF-8"):"");
//					email.setServerAttachPath(StringUtils.isNotBlank(email.getServerAttachPath())?new String(email.getServerAttachPath().getBytes("ISO-8859-1"),"UTF-8"):"");
//					email.setSending(StringUtils.isNotBlank(email.getSending())?new String(email.getSending().getBytes("ISO-8859-1"),"UTF-8"):"");
//					email.setTopic(StringUtils.isNotBlank(email.getTopic())?new String(email.getTopic().getBytes("ISO-8859-1"),"UTF-8"):"");
//					email.setName(StringUtils.isNotBlank(email.getName())?new String(email.getName().getBytes("ISO-8859-1"),"UTF-8"):"");
//					/*String[] atta = new String[email.getFileAffix().length];
//					if(email.getFileAffix() != null && email.getFileAffix().length > 0) {
//						for(int i = 0; i <email.getFileAffix().length;i++) {
//							atta[i] = StringUtils.isNotBlank(email.getFileAffix()[i])?new String(email.getFileAffix()[i].getBytes("ISO-8859-1"),"utf-8"):"";
//						}
//						email.setFileAffix(atta);
//					}*/
//				} catch (UnsupportedEncodingException e) {
//					log.error(e.getMessage());
//				}
//				emailService.sendEmail(email);
//				log.info("QuartzService:scheduledLightSearch2:yesterday="+yesterday+"&email="+JSONObject.toJSONString(email));
//    	}
//    }
    
}
